package com.ytu.clouddisk.face;

import com.ytu.clouddisk.utils.Varibles;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.EditText;
import android.widget.Button;
import android.widget.Toast;

public class AccountConfigActivity extends Activity {

	private EditText etUser;
	private EditText etPsd;
	private Button btnOK;
	private Button btnBack;
	private Button.OnClickListener listener;
	private static SharedPreferences sp;
	private int what;
	private String AccountType;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.account_config);
		init();

		// 获取父活动的值，确定账户类型
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			what = extras.getInt("keyCode");
		}

		switch (what) {
		case Varibles.GOOGLE_REQUEST_CODE:
			setTitle("Google账户设置");
			AccountType = Varibles.GOOGLE_ACCOUNT;
			break;
		case Varibles.VDISK_REQUEST_CODE:
			AccountType = Varibles.VDISK_ACCOUNT;
			setTitle("新浪微盘账户设置");
			break;
		default:
			break;
		}
	}

	protected void init() {
		etUser = (EditText) findViewById(R.id.et_user);
		etPsd = (EditText) findViewById(R.id.et_psd);
		btnOK = (Button) findViewById(R.id.btn_ok);
		btnBack = (Button) findViewById(R.id.btn_back);
		sp = getSharedPreferences("accounts", MODE_PRIVATE);
		listener = new Button.OnClickListener() {

			@Override
			public void onClick(View v) {

				if (v.equals(btnOK)) {
					// 存入XML中
					String user = etUser.getText().toString().trim();
					String psd = etPsd.getText().toString().trim();
					// 空检测
					if (detectEditText(user) || detectEditText(psd)) {
						Toast.makeText(AccountConfigActivity.this, "账号或用户名无效",
								Toast.LENGTH_SHORT).show();
						return;
					}
					Bundle bundle = new Bundle();
					bundle.putBoolean("result",
							sp.edit().putString(AccountType + "User", user)
									.putString(AccountType + "Psd", psd)
									.commit());
					Intent mIntent = new Intent();
					mIntent.putExtras(bundle);
				
					setResult(what, mIntent);
					finish();
				} else if (v.equals(btnBack)) {
					setResult(Varibles.REQUEST_CODE_CANCEL);
					finish();
				}
			}

		};
		// 设置灰色文本
		etUser.setHint("用户名");
		etPsd.setHint("密码");
		btnOK.setOnClickListener(listener);
		btnBack.setOnClickListener(listener);
	}

	/**
	 * 对话框的空检测 无效则返回true
	 */
	protected boolean detectEditText(String et) {
		if (et == null || et == "")
			return true;
		else if (et != null && et != "")
			return false;
		return true;
	}

}
